//
//  XGL_RequestPlugTool.swift
//  Maternal
//
//  Created by ios on 2022/6/1.
//

import Foundation
import Moya
import Alamofire
import PanKit
import SwiftyRSA


class XGL_RequestPlugTool {
    
}

// MARK: - PluginType
extension XGL_RequestPlugTool: PluginType {
    
    public func prepare(_ request: URLRequest, target: TargetType) -> URLRequest {
        
        if request.method == .post{
            switch target.task {
            case .requestParameters:
                guard let body = request.httpBody else {
                    return request
                }
//                let encryptedBody = XGL_PRSA.encryptData(body, publicKey: XGL_EncipherTool.share.cpk)
                do {
                    let publicKey = try PublicKey(base64Encoded: XGL_EncipherTool.share.cpk)
                    let encryptedBody = try ClearMessage(data: body).encrypted(with: publicKey, padding: .PKCS1)
                    let bodyStr = encryptedBody.data.base64EncodedString()
                    var newRequest = request
                    newRequest.httpBody = bodyStr.data(using: .utf8)
                    return newRequest
                } catch {
                print(error)
                }
                print("request path:\(request)")
               
            default:
                break
            }
        }
        return request
    }
    
    public func process(_ result: Result<Moya.Response, MoyaError>, target: TargetType) -> Result<Moya.Response, MoyaError> {
        switch result {
        case .success(let response ):
            if var json = try? response.mapJSON() as? [String: Any],let encryptStatus = json["encryptStatus"] as? NSInteger {
                if encryptStatus == 1{
                    if let content = json["data"] as? String{
                        do {
                            let privateKey = try PrivateKey(base64Encoded: XGL_EncipherTool.share.dpk)
                            let encrypted = try EncryptedMessage(base64Encoded: content)
                            let clear = try encrypted.decrypted(with: privateKey, padding: .PKCS1)
                            let bodyJson = try clear.data.jsonObject() as? [String: Any]
                            json["data"] = bodyJson?["content"]
                            if let newData = json.jsonData(){
                                let newResponse: Moya.Response = Moya.Response(statusCode: response.statusCode, data: newData, request: response.request, response: response.response)
                                return .success(newResponse)
                            }
                        } catch {
                        print(error)
                        }
//                        let responseStr = XGL_PRSA.decryptString(content, privateKey: XGL_EncipherTool.share.dpk)
//                        json["data"] = responseStr?.asDict?["content"]
                       
                    }
                }
            }
            break
        case let .failure(error):
            break
        }
        
        return result
    }
    
}
